{% load static %}
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>投票详情</title>
    <link rel="stylesheet" href="{% static 'polls/style.css' %}">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <div class="container">
        <div class="page-header">
            <h1>{{ question.question_text }}</h1>
            <div class="question-meta">
                <span><i class="fas fa-clock"></i> 发布时间：{{ question.pub_date|date:"Y-m-d H:i" }}</span>
                {% if question.end_date %}
                <span><i class="fas fa-hourglass-end"></i> 截止时间：{{ question.end_date|date:"Y-m-d H:i" }}</span>
                {% endif %}
                <span><i class="fas fa-chart-bar"></i> 总投票数：{{ total_votes }}</span>
            </div>
        </div>

        <div class="stats-container">
            <div class="stat-card">
                <i class="fas fa-poll"></i>
                <div class="stat-info">
                    <span class="stat-value">{{ question.choice_set.count }}</span>
                    <span class="stat-label">选项数量</span>
                </div>
            </div>
            <div class="stat-card">
                <i class="fas fa-users"></i>
                <div class="stat-info">
                    <span class="stat-value">{{ total_votes }}</span>
                    <span class="stat-label">总投票数</span>
                </div>
            </div>
            <div class="stat-card">
                <i class="fas fa-clock"></i>
                <div class="stat-info">
                    <span class="stat-value">{{ question.pub_date|date:"Y-m-d" }}</span>
                    <span class="stat-label">发布日期</span>
                </div>
            </div>
        </div>

        <div class="vote-container">
            <div class="vote-form-container">
                {% if has_voted %}
                    <div class="voted-message">
                        <i class="fas fa-check-circle"></i>
                        <h2>投票成功！</h2>
                        <p>感谢您的参与</p>
                    </div>
                    <div class="vote-actions">
                        <a href="{% url 'polls:detail' question.id %}?revote=true" class="btn btn-primary">
                            <i class="fas fa-redo"></i> 重新投票
                        </a>
                        <a href="{% url 'polls:index' %}" class="btn" style="background: #95a5a6; margin-left: 10px;">
                            <i class="fas fa-list"></i> 返回列表
                        </a>
                    </div>
                {% else %}
                    <form action="{% url 'polls:detail' question.id %}" method="post" class="vote-form" id="voteForm">
                        {% csrf_token %}
                        <fieldset>
                            <legend><h2>参与投票</h2></legend>
                            {% if error_message %}
                                <div class="error-message">
                                    <i class="fas fa-exclamation-circle"></i>
                                    <strong>{{ error_message }}</strong>
                                </div>
                            {% endif %}
                            {% for choice in question.choice_set.all %}
                                <div class="choice-option">
                                    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" class="choice-input">
                                    <label for="choice{{ forloop.counter }}" class="choice-label">
                                        <span class="choice-text">{{ choice.choice_text }}</span>
                                        <span class="choice-votes">{{ choice.votes }} 票</span>
                                    </label>
                                </div>
                            {% endfor %}
                        </fieldset>
                        <div class="form-actions">
                            <button type="submit" class="btn btn-primary" id="submitBtn">
                                <i class="fas fa-vote-yea"></i> 提交投票
                            </button>
                            <a href="{% url 'polls:index' %}" class="btn" style="background: #95a5a6; margin-left: 10px;">
                                <i class="fas fa-list"></i> 返回列表
                            </a>
                        </div>
                    </form>
                    <div class="progress-container" id="progressContainer" style="display: none;">
                        <div class="progress-bar">
                            <div class="progress-fill"></div>
                        </div>
                        <div class="progress-text">正在提交投票...</div>
                    </div>
                {% endif %}
            </div>

            <div class="chart-container">
                <h2>投票统计</h2>
                <canvas id="voteChart"></canvas>
            </div>
        </div>

        {% if messages %}
            <div class="messages">
                {% for message in messages %}
                    <div class="message {{ message.tags }}">
                        <i class="fas fa-info-circle"></i>
                        {{ message }}
                    </div>
                {% endfor %}
            </div>
        {% endif %}
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            var choicesJson = '{{ choices_json|default:"[]"|safe }}';
            console.log('Raw choices JSON:', choicesJson); // 调试信息

            if (choicesJson && choicesJson.trim() !== '' && choicesJson !== 'null') { // 检查是否为空、全为空格或字符串'null'
                try {
                    var choices = JSON.parse(choicesJson);
                    console.log('Parsed Chart data:', choices);  // 调试信息

                    var ctx = document.getElementById('voteChart').getContext('2d');
                    if (!ctx) {
                        console.error('Could not get canvas context');
                        document.querySelector('.chart-container').innerHTML = '<p class="error-message">无法获取图表上下文，请刷新页面。</p>';
                    }

                    // 只有在获取到上下文时才创建图表
                    if (ctx) {
                        new Chart(ctx, {
                            type: 'pie',
                            data: {
                                labels: choices.map(function(choice) { return choice.text; }),
                                datasets: [{
                                    data: choices.map(function(choice) { return choice.votes; }),
                                    backgroundColor: [
                                        'rgba(52, 152, 219, 0.8)',
                                        'rgba(46, 204, 113, 0.8)',
                                        'rgba(155, 89, 182, 0.8)',
                                        'rgba(241, 196, 15, 0.8)',
                                        'rgba(231, 76, 60, 0.8)'
                                    ],
                                    borderColor: [
                                        'rgba(52, 152, 219, 1)',
                                        'rgba(46, 204, 113, 1)',
                                        'rgba(155, 89, 182, 1)',
                                        'rgba(241, 196, 15, 1)',
                                        'rgba(231, 76, 60, 1)'
                                    ],
                                    borderWidth: 1
                                }]
                            },
                            options: {
                                responsive: true,
                                maintainAspectRatio: false,
                                plugins: {
                                    legend: {
                                        position: 'right',
                                        labels: {
                                            padding: 20,
                                            font: {
                                                size: 14
                                            }
                                        }
                                    },
                                    title: {
                                        display: true,
                                        text: '投票结果统计',
                                        font: {
                                            size: 18
                                        },
                                        padding: {
                                            bottom: 20
                                        }
                                    },
                                    tooltip: {
                                        callbacks: {
                                            label: function(context) {
                                                var label = context.label || '';
                                                var value = context.raw || 0;
                                                var total = context.dataset.data.reduce(function(a, b) { return a + b; }, 0);
                                                var percentage = total > 0 ? Math.round((value / total) * 100) : 0;
                                                return label + ': ' + value + ' 票 (' + percentage + '%)';
                                            }
                                        }
                                    }
                                }
                            }
                        });
                    }
                } catch (error) {
                    console.error('Error initializing chart:', error);
                    document.querySelector('.chart-container').innerHTML = '<p class="error-message">图表加载失败，请刷新页面重试</p>';
                }
            } else {
                console.warn('choices_json is empty or invalid. Not rendering chart.');
                document.querySelector('.chart-container').innerHTML = '<p class="error-message">暂无投票数据。</p>';
            }

            // 处理表单提交
            var voteForm = document.getElementById('voteForm');
            if (voteForm) { // 检查元素是否存在
                voteForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    
                    var form = this;
                    var submitBtn = document.getElementById('submitBtn');
                    var progressContainer = document.getElementById('progressContainer');
                    var progressFill = progressContainer.querySelector('.progress-fill');
                    
                    // 显示进度条
                    submitBtn.style.display = 'none';
                    progressContainer.style.display = 'block';
                    
                    // 模拟进度
                    var progress = 0;
                    var interval = setInterval(function() {
                        progress += 5;
                        progressFill.style.width = progress + '%';
                        
                        if (progress >= 100) {
                            clearInterval(interval);
                            form.submit();
                        }
                    }, 100);
                });
            }

            // 自动隐藏消息提示
            const messages = document.querySelectorAll('.message');
            messages.forEach(message => {
                setTimeout(() => {
                    message.style.opacity = '0';
                    setTimeout(() => message.remove(), 300);
                }, 3000);
            });
        });
    </script>
</body>
</html>